<script lang="ts" setup>
  import type { AttrributeVo } from '@/api/product/type'
  import { getParentId } from '@/api/product/attribute'
  import { ref } from 'vue'
  let arrItem = ref<Array<AttrributeVo>>([]) // 用于存储一级分类数据
  let arrItem2 = ref<Array<AttrributeVo>>([]) // 用于存储二级分类数据
  let arrItem3 = ref<Array<AttrributeVo>>([]) // 用于存储三级分类数据
  //收集用户选择的id
  let selectId = ref<string>()
  let selectId2 = ref<string>()
  let selectId3 = ref<string>()
  //引入生命周期函数
  import { onMounted } from 'vue'

  //页面加载时，获取一级分类
  onMounted(() => {
    fetchSubCategories('0')
  })
  //根据parentId获取下一级分类
  async function fetchSubCategories(parentId: string) {
    let result = await getParentId(parentId)
    if (parentId === '0') {
      arrItem.value = result
      selectId2.value = '' // 清空下级
      arrItem2.value = []
      selectId3.value = ''
      arrItem3.value = []
    } else if (selectId.value === parentId) {
      // 说明是一级选中后触发的二级加载
      arrItem2.value = result
      selectId3.value = ''
      arrItem3.value = []
    } else {
      // 是二级选中后触发的三级加载
      arrItem3.value = result
    }
  }
  /**
   * 获取二级数据
   */
  const handleFirstLevelChange = async () => {
    await fetchSubCategories(selectId.value!)
  }
  /**
   * 获取三级数据
   */
  const handleSecondLevelChange = async () => {
    await fetchSubCategories(selectId2.value!)
  }
</script>
<template>
  <el-card>
    <el-form
      :inline="true"
      class="demo-form-inline">
      <el-form-item label="一级分类">
        <el-select
          v-model="selectId"
          @change="handleFirstLevelChange">
          <el-option
            v-for="item in arrItem"
            :key="item.id"
            :value="item.id"
            :label="item.attributeName">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="二级分类">
        <el-select
          v-model="selectId2"
          @change="handleSecondLevelChange">
          <el-option
            v-for="item in arrItem2"
            :key="item.id"
            :value="item.id"
            :label="item.attributeName">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="三级分类">
        <el-select v-model="selectId3">
          <el-option
            v-for="item in arrItem3"
            :key="item.id"
            :value="item.id"
            :label="item.attributeName">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<style scoped>
  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }
</style>
